﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using FisheryPlatform.Common.StaticCache;
using System.Net;
using System.IO;

namespace FisheryPlatform.Bussiness.Cache
{
    public class SiteCacheManager
    {
        public const string SiteNameAdmin = "http://admin.laozhouyuye.com";
        public const string SiteNameWWW = "http://www.laozhouyuye.com";
        public const string CacheSettingsPagePath = "/cache/settings.aspx";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        public static void Settings(HttpRequest request, HttpResponse response)
        {
            #region
            if (string.IsNullOrEmpty(request.Form["at"]) == false)
            {
                #region
                var actionType = request.Form["at"].Trim();
                switch (actionType)
                {
                    case "get_all_cache_keys":
                        response.Write("result:" + CacheDataUtility.Intance.GetAllCacheKeys());
                        break;
                    case "clear_all_cache":
                        CacheDataUtility.Intance.DeleteAll();
                        response.Write("result:ok");
                        break;
                    case "remove_cache_key":
                        var list = request.Form["keys"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var key in list)
                        {
                            CacheDataUtility.Intance.Delete(key);
                        }
                        response.Write("result:ok");
                        break;
                    default: break;
                }
                #endregion
            }
            else
            {
                response.Write("result:fail");
            }
            #endregion
        }

        /// <summary>
        /// 获取站点 缓存keys
        /// </summary>
        /// <param name="siteName"></param>
        /// <returns></returns>
        public static string GetAllCacheKeys(string siteName)
        {
            return SimulationWebRequest(siteName, "at=get_all_cache_keys");
        }

        /// <summary>
        /// 清除站点全部缓存
        /// </summary>
        /// <param name="siteName"></param>
        /// <returns></returns>
        public static string ClearAllCache(string siteName)
        {
            return SimulationWebRequest(siteName, "at=clear_all_cache");
        }

        /// <summary>
        /// 移除指定缓存值
        /// </summary>
        /// <param name="siteName"></param>
        /// <param name="cacheKeys"></param>
        /// <returns></returns>
        public static string RemoveCache(string siteName, string cacheKeys)
        {
            return SimulationWebRequest(siteName, "at=remove_cache_key&keys=" + cacheKeys);
        }

        private static string SimulationWebRequest(string siteName, string value)
        {
            #region
            var resposeText = "";
            try
            {
                //request
                byte[] buffer = ASCIIEncoding.Default.GetBytes(value);
                var url = siteName + CacheSettingsPagePath;
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

                request.Method = "POST";
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)";
                request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                request.ContentLength = buffer.Length;
                //request.ClientCertificates.Add(new X509Certificate2(ConfigSetting.ConfigInfo.CertPath + ConfigSetting.ConfigInfo.CertFileName, ConfigSetting.ConfigInfo.KeyPassword));
                request.KeepAlive = true;
                using (Stream reqStream = request.GetRequestStream())
                {
                    reqStream.Write(buffer, 0, buffer.Length);
                }

                //response
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();

                if (responseStream != null)
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    resposeText = reader.ReadToEnd();
                }
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    resposeText = "";
                }
                response.Close();
            }
            catch (Exception ex)
            {
                ExceptionMessage.Record(ex);
            }
            return resposeText;
            #endregion
        }

    }
}
